//
//  AudioManager.swift
//  Robot
//
//  Created by ming on 2025/2/18.
//

import UIKit
import Combine
import AVFoundation
import SwiftUI

final class AudioManager: NSObject, ObservableObject {
    static let shared = AudioManager()
    private var player: AVPlayer?
    private var session = AVAudioSession.sharedInstance()
    private var canellable: AnyCancellable?
    private var playCallback: ((Bool) -> Void)?
    @Published var isPlay: Bool = false
    
    private func activateSession() {
        do {
            try session.setCategory(.playback, mode: .default, options: [] )
            try session.setActive(true, options: .notifyOthersOnDeactivation)
            try session.overrideOutputAudioPort(.speaker)
        } catch let error {
            print(error.localizedDescription)
        }
    }
    
    func startAudio(urlStr: String, autoPlay: Bool = true) {
        activateSession()
        
        let url = URL(string: urlStr)
        let playerItem: AVPlayerItem = AVPlayerItem(url: url!)
        
        if let player = player {
            player.replaceCurrentItem(with: playerItem)
        } else {
            player = AVPlayer(playerItem: playerItem)
            // 添加 KVO 监听 rate 属性
            player?.addObserver(self, forKeyPath: #keyPath(AVPlayer.rate), options: [.old, .new], context: nil)
        }
        
        canellable = NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime)
            .sink { [weak self] _ in
                guard let me = self else { return }
                me.deactivateSession()
            }
        
        if let player = player, autoPlay {
            player.play()
        }
    }
    
    func startAudio(urlStr: String, autoPlay: Bool = true, playCallback: @escaping (Bool) -> Void) {
        self.playCallback = playCallback
        self.startAudio(urlStr: urlStr, autoPlay: autoPlay)
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == #keyPath(AVPlayer.rate) {
            if let newRate = change?[.newKey] as? Float {
                if newRate == 0 {
                    isPlay = false
                    print("播放器已暂停或停止")
                    playCallback?(false)
                } else {
                    isPlay = true
                    playCallback?(true)
                    print("播放器正在播放")
                }
            }
        }
    }
    
    func deactivateSession() {
        do {
            try session.setActive(false, options: .notifyOthersOnDeactivation)
        } catch let error as NSError {
            print("Failed to deactivate audio session: \(error.localizedDescription)")
        }
    }
    
    func play() {
        if let player = player {
            player.play()
        }
    }
    
    func pause() {
        if let player = player {
            player.pause()
        }
    }
    
    func getPlaybackDuration() -> Double {
        guard let player = player else {
            return 0
        }
        
        return player.currentItem?.duration.seconds ?? 0
    }
    
    deinit {
        canellable?.cancel()
    }
}
